<?php
class MY_Form_validation extends CI_Form_validation
{
	 var $ci;
	
     function __construct($config = array())
     {
          parent::__construct($config);
		  $this->ci =& get_instance();
		  $this->_error_prefix = '<span class="error">';
		  $this->_error_suffix = '</span>';
     }
 
    /**
     * Error Array
     *
     * Returns the error messages as an array
     *
     * @return  array
     */
    function get_error_array()
    {
        if (count($this->_error_array) === 0)
        {
                return FALSE;
        }
        else
            return $this->_error_array;
    }
	
	/**
	 * config/form_validation.php에 있는 rules group의 키를 반환
	 *
	 * @return	array
	 */
	function get_config_rules_group_keys($group){
		$res = array();
		foreach($this->_config_rules[$group] as $i)
			$res[] = $i['field'];
		return $res;
	}
	
	/**
     * Set Error
     *
     * @access  public
     * @param   string
     * @return  bool
    */  

    function set_error($field = 'custom_error', $error = '')
    {
        if (empty($error))
        {
            return FALSE;
        }
        else
        {
            $this->ci->form_validation->_error_array[$field] = $error;
			if(!isset($CI->form_validation->_field_data[$field]))
				$CI->form_validation->_field_data[$field] = array(
					'field'				=> $field,
					'label'				=> null,
					'rules'				=> null,
					'is_array'			=> null,
					'keys'				=> null,
					'postdata'			=> NULL,
					'error'				=> ''
				);
			$this->ci->form_validation->_field_data[$field]['error'] = $error;

            return TRUE;
        }
    }
	
	function valid_phone_number($num)
	{
		if( ! preg_match('/^\d{2,3}-{0,1}\d{3,4}-{0,1}\d{4}$/', $num))
		{
			$this->CI->form_validation->set_message('valid_phone_number', '잘못된 전화번호입니다.');
			return FALSE;
		}
	}
    
    function valid_date($str, $params)
    {
        // setup
        //$CI =&amp;amp;amp;amp;amp; get_instance();
        //$CI
        $params = explode(',', $params);
        $delimiter = $params[1];
        $date_parts = explode($delimiter, $params[0]);

        // get the index (0, 1 or 2) for each part
        $di = $this->_valid_date_part_index($date_parts, 'd');
        $mi = $this->_valid_date_part_index($date_parts, 'm');
        $yi = $this->_valid_date_part_index($date_parts, 'y');

        // regex setup
        $dre = "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)";
        $mre = "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12)";
        $yre = "([0-9]{4})";
        $red = '\\'.$delimiter; // escape delimiter for regex
        $rex = "/^[0]{$red}[1]{$red}[2]$/";

        // do replacements at correct positions
        $rex = str_replace("[{$di}]", $dre, $rex);
        $rex = str_replace("[{$mi}]", $mre, $rex);
        $rex = str_replace("[{$yi}]", $yre, $rex);

        if (preg_match($rex, $str, $matches)) {
        	// skip 0 as it contains full match, check the date is logically valid
            if ($this->_check_valid_date($matches[$yi + 1], $matches[$mi + 1], $matches[$di + 1])) {
                return true;
            } else {
                // match but logically invalid
                $this->CI->form_validation->set_message('valid_date', "잘못된 날짜입니다.");
                return false;
            }
        } 

        // no match
        $this->CI->form_validation->set_message('valid_date', "날짜 형식이 잘못되었습니다.");
        return false;
    }

	function _check_valid_date($year, $month, $day){
		if ($month < 1 || $month > 12) return false;
		if ($day < 1 || $day > 31) return false;
		if (($month == 4 || $month == 6 || $month==9 || $month == 11) && $day == 31) return false;
		if ($month == 2) {
			$is_leap = ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0));
			if ($day > 29 || ($day == 29 && !$is_leap)) return false;
		}
		return true;
	}

    function _valid_date_part_index($parts, $search) {
        for ($i = 0; $i <= count($parts); $i++) {
            if ($parts[$i] == $search) {
                return $i;
            }
        }
    }	
}